package com.lagou.edu.transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Component
public class MyTransactionManager {
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    public Connection getConnection(){
        Connection connection = null;
        if(threadLocal.get()!=null){
            connection = threadLocal.get();
        }else{
            try {
                connection =  dataSource.getConnection();
                threadLocal.set(connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        return  connection;
    }
}
